import express, { Request, Response, Router } from 'express';
import { StockService } from '../services/StockService';
import { StockCategoryService } from '../services/StockCategoryService';
import { aiAnalysisService } from '../services/AIAnalysisService';
import { ResponseHelper as ApiResponse } from '../utils/response';
import { authenticateToken } from '../middleware/auth';

const router: Router = express.Router();
const stockService = new StockService();
const categoryService = new StockCategoryService();


/**
 * @swagger
 * /api/stocks/realtime/{stockId}:
 *   get:
 *     summary: 获取股票实时数据
 *     description: 根据股票ID获取实时股票数据，包含最新价格、涨跌幅等信息
 *     tags: [Stocks]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: path
 *         name: stockId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 股票ID
 *     responses:
 *       200:
 *         description: 成功获取实时数据
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/StockRealtimeResponse'
 *       401:
 *         description: 未授权访问
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 *       404:
 *         description: 股票不存在
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 *       500:
 *         description: 服务器错误
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
router.get('/realtime/:stockId', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { stockId } = req.params;
    const result = await stockService.getRealtimeData(parseInt(stockId));
    
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/history/{stockId}:
 *   get:
 *     summary: 获取股票历史数据
 *     description: 根据股票ID获取历史K线数据
 *     tags: [Stocks]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: path
 *         name: stockId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 股票ID
 *       - in: query
 *         name: startDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始日期 (YYYY-MM-DD)
 *       - in: query
 *         name: endDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束日期 (YYYY-MM-DD)
 *       - in: query
 *         name: period
 *         schema:
 *           type: string
 *           default: daily
 *         description: 数据周期
 *     responses:
 *       200:
 *         description: 成功获取历史数据
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/StockHistoryResponse'
 *       401:
 *         description: 未授权访问
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 *       404:
 *         description: 股票不存在
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 *       500:
 *         description: 服务器错误
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
router.get('/history/:stockId', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { stockId } = req.params;
    const { startDate, endDate, period = 'daily' } = req.query;
    
    const result = await stockService.getHistoryData(parseInt(stockId), {
      startDate: startDate as string,
      endDate: endDate as string,
      period: period as string
    });
    
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/rating/{stockId}:
 *   get:
 *     summary: 获取股票评分
 *     description: 根据股票ID获取最新的股票分析评分
 *     tags: [Stocks]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: path
 *         name: stockId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 股票ID
 *     responses:
 *       200:
 *         description: 成功获取股票评分
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/StockRatingResponse'
 *       401:
 *         description: 未授权访问
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 *       404:
 *         description: 股票不存在
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 *       500:
 *         description: 服务器错误
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
router.get('/rating/:stockId', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { stockId } = req.params;
    const result = await stockService.getStockRating(parseInt(stockId));
    
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/search:
 *   get:
 *     summary: 搜索股票
 *     description: 根据关键词搜索股票（支持股票代码和名称搜索），可指定大分类范围
 *     tags: [Stocks]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: query
 *         name: keyword
 *         required: true
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *       - in: query
 *         name: categoryKey
 *         schema:
 *           type: string
 *           enum: [a_stock, hk_stock, us_stock, uk_stock]
 *         description: 大分类键值，限制搜索范围
 *         example: "a_stock"
 *     responses:
 *       200:
 *         description: 成功搜索股票
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/StockSearchResponse'
 *       400:
 *         description: 搜索关键词不能为空
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 *       401:
 *         description: 未授权访问
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 *       500:
 *         description: 服务器错误
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
router.get('/search', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { keyword, categoryKey } = req.query;
    
    if (!keyword) {
      return ApiResponse.error(res, '搜索关键词不能为空');
    }
    
    const result = await stockService.searchStocks(keyword as string, categoryKey as string);
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/market-overview:
 *   get:
 *     summary: 获取大分类市场概览
 *     description: 获取各个大分类的统计概览信息，包含小分类详情
 *     tags: [Market]
 *     security:
 *       - BearerAuth: []
 *     responses:
 *       200:
 *         description: 成功获取大分类市场概览
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/MarketOverviewResponse'
 *       401:
 *         description: 未授权访问
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 *       500:
 *         description: 服务器错误
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
router.get('/market-overview', authenticateToken, async (_req: Request, res: Response) => {
  try {
    const result = await categoryService.getMainCategoryOverview();
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/market-rating:
 *   get:
 *     summary: 获取大分类评分
 *     description: 基于指定大分类整体表现计算评分（1-10分），支持所有大分类
 *     tags: [Market]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: query
 *         name: mainCategory
 *         schema:
 *           type: string
 *           enum: [a_stock, hk_stock, us_stock, uk_stock]
 *           default: a_stock
 *         description: 大分类代码（a_stock=A股市场,hk_stock=香港市场,us_stock=美股市场,uk_stock=英股市场）
 *     responses:
 *       200:
 *         description: 成功获取大分类评分
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/MarketRatingResponse'
 *       401:
 *         description: 未授权访问
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 *       500:
 *         description: 服务器错误
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
router.get('/market-rating', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { mainCategory } = req.query;
    const result = await categoryService.getMainCategoryRating(mainCategory as string);
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/rise-fall-distribution:
 *   get:
 *     summary: 获取大分类涨跌分布统计
 *     description: 获取指定大分类涨跌停及各涨跌幅区间的股票分布统计，支持所有大分类
 *     tags: [Market]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: query
 *         name: mainCategory
 *         schema:
 *           type: string
 *           enum: [a_stock, hk_stock, us_stock, uk_stock]
 *           default: a_stock
 *         description: 大分类代码（a_stock=A股市场,hk_stock=香港市场,us_stock=美股市场,uk_stock=英股市场）
 *     responses:
 *       200:
 *         description: 成功获取大分类涨跌分布统计
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/RiseFallDistributionResponse'
 *       500:
 *         description: 服务器错误
 */
router.get('/rise-fall-distribution', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { mainCategory } = req.query;
    const result = await categoryService.getMainCategoryRiseFallDistribution(mainCategory as string);
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/main-categories:
 *   get:
 *     summary: 获取大分类列表
 *     description: 获取所有可用的股票大分类（A股、香港、美股等）
 *     tags: [Stock Categories]
 *     security:
 *       - BearerAuth: []
 *     responses:
 *       200:
 *         description: 成功获取大分类列表
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/MainCategoriesResponse'
 *       500:
 *         description: 服务器错误
 */
router.get('/main-categories', authenticateToken, async (_req: Request, res: Response) => {
  try {
    const result = await categoryService.getMainCategories();
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/sub-categories/{mainCategoryKey}:
 *   get:
 *     summary: 获取小分类列表
 *     description: 根据大分类key获取对应的小分类列表
 *     tags: [Stock Categories]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: path
 *         name: mainCategoryKey
 *         required: true
 *         schema:
 *           type: string
 *           enum: [a_stock, hk_stock, us_stock, uk_stock]
 *         description: 大分类键值
 *         example: "a_stock"
 *     responses:
 *       200:
 *         description: 成功获取小分类列表
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/SubCategoriesResponse'
 *       404:
 *         description: 大分类不存在
 *       500:
 *         description: 服务器错误
 */
router.get('/sub-categories/:mainCategoryKey', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { mainCategoryKey } = req.params;
    const result = await categoryService.getSubCategories(mainCategoryKey);
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/category/{subCategoryKey}:
 *   get:
 *     summary: 按小分类获取股票列表
 *     description: 根据小分类key获取对应的股票列表，支持分页
 *     tags: [Stock Categories]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: path
 *         name: subCategoryKey
 *         required: true
 *         schema:
 *           type: string
 *           enum: [sh_a, sz_a, cy, kc, bj, hk_main, hk_gem, nasdaq, nyse, lse]
 *         description: 小分类键值
 *         example: "sh_a"
 *       - in: query
 *         name: pageIndex
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码（从1开始）
 *       - in: query
 *         name: pageSize
 *         schema:
 *           type: integer
 *           default: 20
 *           minimum: 1
 *           maximum: 100
 *         description: 每页条数（最大100条）
 *     responses:
 *       200:
 *         description: 成功获取小分类股票列表
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/CategoryStocksResponse'
 *       404:
 *         description: 小分类不存在
 *       500:
 *         description: 服务器错误
 */
router.get('/category/:subCategoryKey', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { subCategoryKey } = req.params;
    const { pageIndex = 1, pageSize = 20 } = req.query;
    
    // 验证分页参数
    const pageIndexNum = Math.max(1, parseInt(pageIndex as string) || 1);
    const pageSizeNum = Math.min(100, Math.max(1, parseInt(pageSize as string) || 20));
    
    const result = await categoryService.getStocksBySubCategory(
      subCategoryKey,
      pageIndexNum,
      pageSizeNum
    );
    
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/main-category/{mainCategoryKey}/all:
 *   get:
 *     summary: 获取大分类下所有股票
 *     description: 根据大分类key获取该分类下所有股票列表，支持分页
 *     tags: [Stock Categories]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: path
 *         name: mainCategoryKey
 *         required: true
 *         schema:
 *           type: string
 *           enum: [a_stock, hk_stock, us_stock, uk_stock]
 *         description: 大分类键值
 *         example: "a_stock"
 *       - in: query
 *         name: pageIndex
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码（从1开始）
 *       - in: query
 *         name: pageSize
 *         schema:
 *           type: integer
 *           default: 20
 *           minimum: 1
 *           maximum: 100
 *         description: 每页条数（最大100条）
 *     responses:
 *       200:
 *         description: 成功获取大分类下所有股票
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/MainCategoryAllStocksResponse'
 *       404:
 *         description: 大分类不存在
 *       500:
 *         description: 服务器错误
 */
router.get('/main-category/:mainCategoryKey/all', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { mainCategoryKey } = req.params;
    const { pageIndex = 1, pageSize = 20 } = req.query;
    
    // 验证分页参数
    const pageIndexNum = Math.max(1, parseInt(pageIndex as string) || 1);
    const pageSizeNum = Math.min(100, Math.max(1, parseInt(pageSize as string) || 20));
    
    const result = await categoryService.getStocksByMainCategory(
      mainCategoryKey,
      pageIndexNum,
      pageSizeNum
    );
    
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/category-stats:
 *   get:
 *     summary: 获取大分类统计信息
 *     description: 获取所有大分类和小分类的股票数量统计
 *     tags: [Stock Categories]
 *     security:
 *       - BearerAuth: []
 *     responses:
 *       200:
 *         description: 成功获取分类统计
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/CategoryStatsResponse'
 *       500:
 *         description: 服务器错误
 */
router.get('/category-stats', authenticateToken, async (_req: Request, res: Response) => {
  try {
    const result = await categoryService.getMainCategoryStats();
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/sub-category-stats/{subCategoryKey}:
 *   get:
 *     summary: 获取小分类统计信息
 *     description: 获取指定小分类的详细统计信息
 *     tags: [Stock Categories]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: path
 *         name: subCategoryKey
 *         required: true
 *         schema:
 *           type: string
 *           enum: [sh_a, sz_a, cy, kc, bj, hk_main, hk_gem, nasdaq, nyse, lse]
 *         description: 小分类键值
 *         example: "sh_a"
 *     responses:
 *       200:
 *         description: 成功获取小分类统计
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/SubCategoryStatsResponse'
 *       404:
 *         description: 小分类不存在
 *       500:
 *         description: 服务器错误
 */
router.get('/sub-category-stats/:subCategoryKey', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { subCategoryKey } = req.params;
    const result = await categoryService.getSubCategoryStats(subCategoryKey);
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/limit-up-down:
 *   get:
 *     summary: 获取涨跌停统计
 *     description: 获取当前涨停和跌停股票的详细统计信息，包括股票列表
 *     tags: [Market]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: query
 *         name: mainCategory
 *         schema:
 *           type: string
 *           enum: [a_stock, hk_stock, us_stock, uk_stock]
 *         description: 大分类键值，可选，不填则默认为A股市场
 *     responses:
 *       200:
 *         description: 成功获取涨跌停统计
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/LimitUpDownResponse'
 *       401:
 *         description: 未授权访问
 *       404:
 *         description: 市场不存在
 *       500:
 *         description: 服务器错误
 */
router.get('/limit-up-down', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { mainCategory } = req.query;
    const result = await stockService.getLimitUpDown(mainCategory as string);
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/yesterday-limit-return:
 *   get:
 *     summary: 获取昨日涨停今日收益统计
 *     description: 获取昨日涨停股票的今日表现统计，包括涨跌分布和具体股票信息
 *     tags: [Market]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: query
 *         name: mainCategory
 *         schema:
 *           type: string
 *           enum: [a_stock, hk_stock, us_stock, uk_stock]
 *         description: 大分类键值，可选，不填则默认为A股市场
 *     responses:
 *       200:
 *         description: 成功获取昨日涨停今日收益统计
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/YesterdayLimitReturnResponse'
 *       401:
 *         description: 未授权访问
 *       404:
 *         description: 市场不存在
 *       500:
 *         description: 服务器错误
 */
router.get('/yesterday-limit-return', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { mainCategory } = req.query;
    const result = await stockService.getYesterdayLimitUpTodayReturn(mainCategory as string);
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/ai-analysis/{stockId}:
 *   get:
 *     summary: 获取股票AI智能分析
 *     description: 基于DeepSeek AI对指定股票进行综合智能分析，包含投资建议、风险评估等
 *     tags: [AI Analysis]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: path
 *         name: stockId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 股票ID
 *       - in: query
 *         name: refresh
 *         schema:
 *           type: boolean
 *           default: false
 *         description: 是否强制刷新分析结果
 *     responses:
 *       200:
 *         description: 成功获取AI分析结果
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/StockAIAnalysisResponse'
 *       401:
 *         description: 未授权访问
 *       404:
 *         description: 股票不存在
 *       500:
 *         description: 服务器错误或AI分析失败
 */
router.get('/ai-analysis/:stockId', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { stockId } = req.params;
    const { refresh = false } = req.query;
    
    const result = await aiAnalysisService.getStockAIAnalysis(
      parseInt(stockId), 
      refresh === 'true'
    );
    
    if (!result) {
      return ApiResponse.error(res, '未找到股票AI分析数据', 404);
    }
    
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/category-ai-analysis/{categoryKey}:
 *   get:
 *     summary: 获取大分类AI智能分析
 *     description: 基于DeepSeek AI对指定大分类市场进行整体智能分析
 *     tags: [AI Analysis]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: path
 *         name: categoryKey
 *         required: true
 *         schema:
 *           type: string
 *           enum: [a_stock, hk_stock, us_stock, uk_stock]
 *         description: 大分类键值
 *         example: "a_stock"
 *       - in: query
 *         name: refresh
 *         schema:
 *           type: boolean
 *           default: false
 *         description: 是否强制刷新分析结果
 *     responses:
 *       200:
 *         description: 成功获取大分类AI分析结果
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/CategoryAIAnalysisResponse'
 *       401:
 *         description: 未授权访问
 *       404:
 *         description: 大分类不存在
 *       500:
 *         description: 服务器错误或AI分析失败
 */
router.get('/category-ai-analysis/:categoryKey', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { categoryKey } = req.params;
    const { refresh = false } = req.query;
    
    // 验证categoryKey
    const validCategories = ['a_stock', 'hk_stock', 'us_stock', 'uk_stock'];
    if (!validCategories.includes(categoryKey)) {
      return ApiResponse.error(res, '无效的大分类键值', 400);
    }
    
    const result = await aiAnalysisService.getCategoryAIAnalysis(
      categoryKey, 
      refresh === 'true'
    );
    
    if (!result) {
      return ApiResponse.error(res, '未找到大分类AI分析数据', 404);
    }
    
    return ApiResponse.success(res, result);
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/batch-ai-analysis:
 *   post:
 *     summary: 批量刷新股票AI分析
 *     description: 批量刷新指定股票的AI分析结果，用于定时任务或手动更新
 *     tags: [AI Analysis]
 *     security:
 *       - BearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               stockIds:
 *                 type: array
 *                 items:
 *                   type: integer
 *                 description: 股票ID数组
 *                 example: [1, 2, 3, 4, 5]
 *             required:
 *               - stockIds
 *     responses:
 *       200:
 *         description: 批量分析完成
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/BatchAIAnalysisResponse'
 *       400:
 *         description: 请求参数错误
 *       401:
 *         description: 未授权访问
 *       500:
 *         description: 服务器错误
 */
router.post('/batch-ai-analysis', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { stockIds } = req.body;
    
    if (!Array.isArray(stockIds) || stockIds.length === 0) {
      return ApiResponse.error(res, '股票ID数组不能为空', 400);
    }
    
    // 限制批量数量避免超时
    if (stockIds.length > 50) {
      return ApiResponse.error(res, '单次批量分析股票数量不能超过50个', 400);
    }
    
    const result = await aiAnalysisService.batchRefreshStockAnalysis(stockIds);
    
    return ApiResponse.success(res, result, '批量AI分析任务完成');
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

/**
 * @swagger
 * /api/stocks/batch-category-ai-analysis:
 *   post:
 *     summary: 批量刷新大分类AI分析
 *     description: 批量刷新所有大分类的AI分析结果
 *     tags: [AI Analysis]
 *     security:
 *       - BearerAuth: []
 *     responses:
 *       200:
 *         description: 批量分析完成
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/BatchAIAnalysisResponse'
 *       401:
 *         description: 未授权访问
 *       500:
 *         description: 服务器错误
 */
router.post('/batch-category-ai-analysis', authenticateToken, async (_req: Request, res: Response) => {
  try {
    const categoryKeys = ['a_stock', 'hk_stock', 'us_stock', 'uk_stock'];
    
    const result = await aiAnalysisService.batchRefreshCategoryAnalysis(categoryKeys);
    
    return ApiResponse.success(res, result, '批量大分类AI分析任务完成');
  } catch (error: any) {
    return ApiResponse.error(res, error.message);
  }
});

export default router;